import 'dart:io';
import 'package:docx_to_text/docx_to_text.dart';
import 'package:path/path.dart' as path;

/// DOCX文件读取服务
class DocxReaderService {
  static final DocxReaderService _instance = DocxReaderService._internal();
  factory DocxReaderService() => _instance;
  DocxReaderService._internal();

  /// 读取DOCX文件内容
  Future<DocxContent> readDocxFile(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) {
        throw Exception('DOCX文件不存在: $filePath');
      }

      print('DocxReaderService: 开始读取DOCX文件: $filePath');
      
      // 读取文件字节
      final bytes = await file.readAsBytes();
      
      // 使用docx_to_text包解析DOCX内容
      final text = docxToText(bytes);
      
      if (text.isEmpty) {
        throw Exception('DOCX文件内容为空或无法解析');
      }

      // 获取文件信息
      final fileName = path.basenameWithoutExtension(filePath);
      final fileSize = await file.length();
      final lastModified = await file.lastModified();

      print('DocxReaderService: DOCX文件读取成功，内容长度: ${text.length}字符');

      return DocxContent(
        fileName: fileName,
        filePath: filePath,
        content: text,
        fileSize: fileSize,
        lastModified: lastModified,
      );

    } catch (e) {
      print('DocxReaderService: 读取DOCX文件失败: $e');
      rethrow;
    }
  }

  /// 提取DOCX文件的摘要信息
  Future<String> extractSummary(String filePath, {int maxLength = 500}) async {
    try {
      final docxContent = await readDocxFile(filePath);
      final content = docxContent.content;

      if (content.length <= maxLength) {
        return content;
      }

      // 尝试在句号处截断，保持完整性
      final truncated = content.substring(0, maxLength);
      final lastSentenceEnd = truncated.lastIndexOf(RegExp(r'[。！？.!?]'));
      
      if (lastSentenceEnd > maxLength * 0.7) {
        return truncated.substring(0, lastSentenceEnd + 1) + '...';
      } else {
        return truncated + '...';
      }

    } catch (e) {
      print('DocxReaderService: 提取摘要失败: $e');
      return '无法读取DOCX文件内容';
    }
  }

  /// 搜索DOCX文件中的关键词
  Future<List<SearchResult>> searchInDocx(String filePath, String keyword) async {
    try {
      final docxContent = await readDocxFile(filePath);
      final content = docxContent.content;
      final results = <SearchResult>[];

      if (keyword.isEmpty) {
        return results;
      }

      final lines = content.split('\n');
      for (int i = 0; i < lines.length; i++) {
        final line = lines[i];
        if (line.toLowerCase().contains(keyword.toLowerCase())) {
          results.add(SearchResult(
            lineNumber: i + 1,
            content: line.trim(),
            keyword: keyword,
          ));
        }
      }

      print('DocxReaderService: 在DOCX文件中找到${results.length}个匹配项');
      return results;

    } catch (e) {
      print('DocxReaderService: 搜索失败: $e');
      return [];
    }
  }

  /// 获取DOCX文件的基本信息
  Future<DocxFileInfo> getDocxFileInfo(String filePath) async {
    try {
      final file = File(filePath);
      if (!await file.exists()) {
        throw Exception('DOCX文件不存在: $filePath');
      }

      final fileName = path.basename(filePath);
      final fileSize = await file.length();
      final lastModified = await file.lastModified();
      final created = await file.lastAccessed(); // 近似创建时间

      // 尝试读取内容以获取更多信息
      String contentPreview = '';
      int wordCount = 0;
      int paragraphCount = 0;

      try {
        final docxContent = await readDocxFile(filePath);
        final content = docxContent.content;
        
        // 生成内容预览
        contentPreview = content.length > 200 
            ? content.substring(0, 200) + '...'
            : content;

        // 统计字数和段落数
        wordCount = content.split(RegExp(r'\s+')).where((word) => word.isNotEmpty).length;
        paragraphCount = content.split('\n').where((line) => line.trim().isNotEmpty).length;

      } catch (e) {
        print('DocxReaderService: 无法读取文件内容进行统计: $e');
        contentPreview = '无法预览内容';
      }

      return DocxFileInfo(
        fileName: fileName,
        filePath: filePath,
        fileSize: fileSize,
        lastModified: lastModified,
        created: created,
        contentPreview: contentPreview,
        wordCount: wordCount,
        paragraphCount: paragraphCount,
      );

    } catch (e) {
      print('DocxReaderService: 获取文件信息失败: $e');
      rethrow;
    }
  }
}

/// DOCX文件内容数据类
class DocxContent {
  final String fileName;
  final String filePath;
  final String content;
  final int fileSize;
  final DateTime lastModified;

  DocxContent({
    required this.fileName,
    required this.filePath,
    required this.content,
    required this.fileSize,
    required this.lastModified,
  });

  /// 格式化文件大小
  String get formattedFileSize {
    if (fileSize < 1024) {
      return '$fileSize B';
    } else if (fileSize < 1024 * 1024) {
      return '${(fileSize / 1024).toStringAsFixed(1)} KB';
    } else {
      return '${(fileSize / (1024 * 1024)).toStringAsFixed(1)} MB';
    }
  }

  /// 格式化修改时间
  String get formattedLastModified {
    return '${lastModified.year}-${lastModified.month.toString().padLeft(2, '0')}-${lastModified.day.toString().padLeft(2, '0')} ${lastModified.hour.toString().padLeft(2, '0')}:${lastModified.minute.toString().padLeft(2, '0')}';
  }

  /// 获取字数统计
  int get wordCount {
    return content.split(RegExp(r'\s+')).where((word) => word.isNotEmpty).length;
  }

  /// 获取段落数
  int get paragraphCount {
    return content.split('\n').where((line) => line.trim().isNotEmpty).length;
  }
}

/// 搜索结果数据类
class SearchResult {
  final int lineNumber;
  final String content;
  final String keyword;

  SearchResult({
    required this.lineNumber,
    required this.content,
    required this.keyword,
  });

  /// 高亮显示关键词
  String get highlightedContent {
    return content.replaceAllMapped(
      RegExp(keyword, caseSensitive: false),
      (match) => '**${match.group(0)}**',
    );
  }
}

/// DOCX文件信息数据类
class DocxFileInfo {
  final String fileName;
  final String filePath;
  final int fileSize;
  final DateTime lastModified;
  final DateTime created;
  final String contentPreview;
  final int wordCount;
  final int paragraphCount;

  DocxFileInfo({
    required this.fileName,
    required this.filePath,
    required this.fileSize,
    required this.lastModified,
    required this.created,
    required this.contentPreview,
    required this.wordCount,
    required this.paragraphCount,
  });

  /// 格式化文件大小
  String get formattedFileSize {
    if (fileSize < 1024) {
      return '$fileSize B';
    } else if (fileSize < 1024 * 1024) {
      return '${(fileSize / 1024).toStringAsFixed(1)} KB';
    } else {
      return '${(fileSize / (1024 * 1024)).toStringAsFixed(1)} MB';
    }
  }
} 